package cn.hgj.controller;

import cn.hgj.entity.Order;
import cn.hgj.enums.OrderEvent;
import cn.hgj.repository.OrderRepository;
import cn.hgj.service.DistributedLockService;
import cn.hgj.service.OrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

//@RestController
@RequestMapping("/seckill")
@RequiredArgsConstructor
public class SeckillController {

    private final DistributedLockService lockService;

    private final OrderService orderService;

    private final RabbitTemplate rabbitTemplate;

    private final OrderRepository orderRepository;

    @GetMapping("/list")
    public Object list(){
        return orderRepository.findAll();
    }

    @GetMapping
    public String send(String msg){
        rabbitTemplate.convertAndSend("order.process.queue","你好："+msg);
        rabbitTemplate.convertAndSend("test","你好："+msg);
        return "success";
    }

    @RabbitListener(queues = "order.process.queue")
    public void c(Object msg){
        System.out.println(msg);
    }

    @RabbitListener(queues = "test")
    public void t(String msg){
        System.out.println(msg);
    }


    @PostMapping
    public ResponseEntity<String> seckill(@RequestBody Order order) {

        String lockKey = "seckill:" + order.getProductId();

        return lockService.executeWithLock(lockKey, 3, 10, () -> {
            // 1. 检查库存
//            int stock = 0;//productService.getStock(productId);
//            if (stock < quantity) {
//                throw new RuntimeException("Insufficient stock");
//            }

            // 2. 创建订单
            Order o = orderService.createOrder(order.getUserId(),order.getProductId(),order.getQuantity(),order.getAmount());

            // 3. 扣减库存
            //productService.reduceStock(productId, quantity);

            return ResponseEntity.ok(o.getOrderId());
        });
    }

    @GetMapping("/cancel")
    public ResponseEntity<String> cancelOrder(String orderId,String reason) {
        orderService.cancelOrder(orderId,reason);
        return ResponseEntity.ok("");
    }
}
